<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TypeScript Demo</title>
</head>

<body>

    <label for="inpTxt"></label><input id="inpTxt" name="inpTxt" type="text">
    <input id="click" type="button" value="发送">


    <script type="module">
        import { io } from "./node_modules/socket.io/client-dist/socket.io.esm.min.js";

        let btn = document.getElementById("click");
        let inp = document.getElementById("inpTxt");

        let frame = 0;
        let isOpen = false;
        let testWsFlag = false;
        let socket = null;
        let ws = null;

        if (testWsFlag) {
            console.log('websocket 测试');
            execWebSocket()
        } else {
            console.log('socket.io 测试');
            execSocketIo()
        }

        btn.onclick = () => {
            if (testWsFlag) {
                // ws.close(1000,"gwgwg");  //关闭websocket连接
                // console.log(inp.value);
                // console.log(ws.readyState);
                if (!ws || ws.readyState == 2 || !isOpen) {
                    ws.onopen = function (res) {
                        console.log('连接成功');
                        console.log(res);
                        isOpen = true;
                        ws.send("服务器你好");
                    }
                }
                ws.send(inp.value);
            } else {
                socket.emit('sends', inp.value);
            }
        }

        function execSocketIo() {
            socket = io.connect("ws://127.0.0.1:3000");
            //监听客户端事件推送
            socket.on("connect", () => {
                console.log("连接成功--socketID: ", socket.id);
                socket.emit('sends', socket.id);
            });
            //监听msg数据对象
            socket.on("msg", (arg) => {
                console.log("客户端监听的：" + arg);
            });
            //监听连接关闭推送
            socket.on("disconnect", () => {
                console.log("断开连接: ", socket.id);
            });
        }

        function execWebSocket() {
            ws = new WebSocket('ws://localhost:3000');
            //监听建立连接
            ws.onopen = function (res) {
                console.log('连接成功');
                console.log(res);
                isOpen = true;
                ws.send("服务器你好");
            }
            //监听消息
            ws.onmessage = function (res) {
                console.log('客户端接收到了服务端发来的消息');
                console.log(res);
            }
            ws.onclose = function (e) {
                console.log('closing');
                console.log(e);
                isOpen = false;
            };
            ws.onerror = function (e) {
                console.log('error');
                console.log(e);
            }
        }
    </script>
</body>

</html>